Leer datos del csv y juntar con sales para incluir las variables.
data <- read.csv("test.csv")
datasample <- read.csv("sample_submission.csv")
data_analysis <- merge(data, datasample, by="Id")
suppressWarnings(hopkins(data_hop))
## [1] 1
El valor del estadístico de hopkins está alejado de 0.5 por lo que los datos no son aleatorios hay altas posibilidades de que sea factible el agrupamiento. Ademas vemos que alcanza a 1 lo cual significa que si hay tendencia fuerte de agrupamientos
datos_dist<- dist(data_hop)
fviz_dist(datos_dist, show_labels = F)
Como se puede observar en la VAT, sí existen ciertos patrones que el estadistico de hopkins da.
wss=0
for (i in 1:10)
wss[i] <- sum(kmeans(na.omit(data_analysis), centers=i)$withinss)
plot(1:10, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares")
En este caso podemos observar que el numero de clusters a elegir es 3
como se observa en la gráfica ya que esta empezando a reducir su decenso
a llegar a uno estable.
fviz_nbclust(na.omit(data_analysis), kmeans, method = "wss") +
labs(subtitle = "Elbow method")
Nuevamente para confirmar que si es el numero de clusters, si se observa que actua como la grafica anterior donde el cluster k 3 no tiene un mayor desenso.
km<-kmeans(na.omit(data_analysis),3,iter.max =100)
data_analysis<- na.omit(data_analysis)
data_analysis$grupo<-km$cluster
fviz_cluster(km, data = na.omit(data_hop) ,geom = "point", ellipse.type = "norm")
Se observa que el segundo cluster se traslapa del cluster tercer y
primer donde se ve que hay un segmento que si se juntan. Lo cual puede
significar que las variables no son tan distintas. Cabe recalcar que el
cluster 2 y 3 pueden ser distintas pero son pocas las diferencias.
km$size
## [1] 644 347 155
Se observa que el primer cluster tiene 653 puntos, segundo cluster tiene 144 puntos y el tercero cluster tiene 349 puntos. Esto puede significar que el primer cluster al tener mayor cantidad de datos puede que esten distribuidos de manera uniforme entre los clusters.
km$withinss
## [1] 23622998411 20744978676 34634214706
Se observa que hay mayor cantidad en el cluster 2 pero como vemos en la grafica con anterioridad el numero de clusters se debe reducir a 2.
km<-kmeans(na.omit(data_analysis),2,iter.max =100)
data_analysis<- na.omit(data_analysis)
data_analysis$grupo<-km$cluster
fviz_cluster(km, data = na.omit(data_hop) ,geom = "point", ellipse.type = "norm")
Se observa que el segundo cluster se traslapa del primer cluster donde
se ve que hay un segmento que si se juntan. Lo cual puede significar que
las variables no son tan distintas como habia mencionado
anteriormente.
km$size
## [1] 629 517
Se observa que el primer cluster tiene 526 puntos, segundo cluster tiene 620 puntos lo cual no se alejan de uno al otro a diferencia de los 3 clusters elegidos.
km$withinss
## [1] 99774526450 43634356963
Aunque podemos observar que withinss tiene mas diferencia puede ser comparado el segundo cluster como el doble del cluster 1. Se puede inferir que los puntos del cluster dos estan más ceparados a comparación del cluster 1.
m<-data.frame(withinss=km$withinss, size=km$size)
ggplot(m, aes(size,withinss))+
geom_point()+
geom_smooth(method="lm")+
labs(x="cardinalidad (size)",y="magnitud (whithinss)")+
geom_text_repel(label=rownames(m))
## `geom_smooth()` using formula = 'y ~ x'
## Warning in qt((1 - level)/2, df): Se han producido NaNs
## Warning in max(ids, na.rm = TRUE): ningun argumento finito para max; retornando
## -Inf
Se puede inferir de los 2 grupos, no se alejan demasiado de la línea
recta por lo que podríamos decir que no existen grupos anómalos.
data_analysis <- as.data.frame(data_analysis)
data_analysis <- na.omit(data_analysis)
data_analysis$grupo<-as.factor(data_analysis$grupo)
ggpairs(data_analysis[, c(1:5, 38)],
aes(col = factor(grupo)),
progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
data_analysis <- as.data.frame(data_analysis)
data_analysis <- na.omit(data_analysis)
data_analysis$grupo<-as.factor(data_analysis$grupo)
ggpairs(data_analysis[, c(7:12, 38)],
aes(col = factor(grupo)),
progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
data_analysis <- as.data.frame(data_analysis)
data_analysis <- na.omit(data_analysis)
data_analysis$grupo<-as.factor(data_analysis$grupo)
ggpairs(data_analysis[, c(13:18, 38)],
aes(col = factor(grupo)),
progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
data_analysis <- as.data.frame(data_analysis)
data_analysis <- na.omit(data_analysis)
data_analysis$grupo<-as.factor(data_analysis$grupo)
ggpairs(data_analysis[, c(19:24, 38)],
aes(col = factor(grupo)),
progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
data_analysis <- as.data.frame(data_analysis)
data_analysis <- na.omit(data_analysis)
data_analysis$grupo<-as.factor(data_analysis$grupo)
ggpairs(data_analysis[, c(25:30, 38)],
aes(col = factor(grupo)),
progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
data_analysis <- as.data.frame(data_analysis)
data_analysis <- na.omit(data_analysis)
data_analysis$grupo<-as.factor(data_analysis$grupo)
ggpairs(data_analysis[, c(31:34, 38)],
aes(col = factor(grupo)),
progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
data_analysis <- as.data.frame(data_analysis)
data_analysis <- na.omit(data_analysis)
data_analysis$grupo<-as.factor(data_analysis$grupo)
ggpairs(data_analysis[, c(35:37, 38)],
aes(col = factor(grupo)),
progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
data_analysis <- as.data.frame(data_analysis)
data_analysis <- na.omit(data_analysis)
data_analysis$grupo<-as.factor(data_analysis$grupo)
ggpairs(data_analysis[, c(1:37, 38)],
aes(col = factor(grupo)),
progress = FALSE)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
En la gráfica en general de las 38 variables no se puede observar alguna significancia, aunque podemos observar que las variable de 31 a 34 sus correlancias son muy bajas a comparación de las otras gráficas.
library(flexclust)
## Cargando paquete requerido: grid
## Cargando paquete requerido: lattice
## Cargando paquete requerido: modeltools
## Cargando paquete requerido: stats4
##
## Adjuntando el paquete: 'flexclust'
## The following object is masked from 'package:e1071':
##
## bclust
set.seed(123)
res<-kcca(na.omit(data_hop),2)
## Found more than one class "kcca" in cache; using the first, from namespace 'kernlab'
## Also defined by 'flexclust'
## Found more than one class "kcca" in cache; using the first, from namespace 'kernlab'
## Also defined by 'flexclust'
importance <- FeatureImpCluster(res, as.data.table(na.omit(data_hop)))
plot(importance)
Las variables con tasas de error más bajas (0.00) son más importantes
para el modelo, ya que contribuyen menos a las predicciones incorrectas.
En este caso, variables como “YearBuilt”, “GarageYrBlt”, “OverallQual”,
“TotalBsmtSF” y “GrLivArea” parecen tener un buen desempeño. Las
variables con tasas de error más altas ( x >= 0.00) son menos
importantes, ya que contribuyen más a las predicciones incorrectas.
Variables como “PoolArea”, “MiscVal”, “X3SsnPorch” y “KitchenAbvGr”
parecen tener un desempeño pobre.
barplot(res, bycluster=T, cex.names = 0.2)
Como se puede observar en los dos clusters. Al comparar podemos observar que cada uno de ellos es lo contrario. Ahora inferimos que para “SalePrice” es significativamente más alta en el Cluster 2 que en el Cluster 1, esto sugiere que las viviendas en el Cluster 2 tienden a tener precios de venta más altos que las viviendas en el Cluster 1. Si la barra para “LotArea” es más alta en el Cluster 1 que en el Cluster 2, esto sugiere que las viviendas en el Cluster 1 tienden a tener lotes más grandes que las viviendas en el Cluster 2.
fviz_cluster(km,
data_analysis,
labelsize = 6,
choose.vars = c("SalePrice","LotArea"),
main="k=2 grupos")
por lo tanto se realiza una comparacion ante las dos variables de
salePrice y Lot Area donde se tiende a agrupar propiedades con precios
de venta bajos y áreas de lote más pequeñas. Mientras que el otro
cluster tiende a agrupar propiedades con precios de venta más altos y
áreas de lote más grandes.
silkm<-silhouette(km$cluster,dist(data_analysis))
mean(silkm[,2]) #0.45, no es la mejor partición pero no está mal
## [1] 1.548866
matriz_dist<- dist(data_analysis)
hc<-hclust(datos_dist, method = "ward.D2") #Genera el clustering jerárquico de los datos
plot(hc, cex=0.5, axes=FALSE) #Genera el dendograma
rect.hclust(hc,k=2)
fviz_dend(hc,k=2, cex = .2, horiz = T)
``` r
fviz_dend(hc, k=2, color_labels_by_k = T, cex = .4 ,type = "phylogenic", repel = T)
A partir de los dos clusters elegidos, se puede examinar las
características de los puntos de datos dentro de cada uno para entender
sus similitudes y diferencias.